import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from 'vue-router'

import { RouteMaps } from './routeMap'

export const NotFoundRoute = {
  path: '/:catchAll(.*)',
  redirect: '/404',
}

export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
    },
  },
  // {
  //   path: '/',
  //   component: () => import('@/layout/index.vue'),
  //   children: [
  //     {
  //       path: '/crf',
  //       component: () => import('@/components/FormDesign/index.vue'),
  //     },
  //     {
  //       path: '/project/crfdesign',
  //       component: () => import('@/views/project/ecrf-design/index.vue'),
  //     },
  //   ],
  // },
  // {
  //   path: '/project/data',
  //   component: import('@/views/project/example/index.vue'),
  // },
]

const router = createRouter({
  history:
    import.meta.env.VITE_ROUTER_HISTORY === 'hash'
      ? createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH)
      : createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes: constantRoutes,
})

export const generateRoutes = (routes: Array<any>) => {
  console.log('r', routes)
  const res: Array<RouteRecordRaw> = []
  routes.forEach((route) => {
    const { path, component, title, icon, visible, noCache, redirect } = route
    const currentRoute: RouteRecordRaw = {
      path: path || '/',
      component: RouteMaps[component] || RouteMaps.layout,
      meta: {
        title,
        icon,
        hidden: !visible,
        keepAlive: !noCache,
      },
    }
    redirect && (currentRoute.redirect = redirect)

    if (!route.children) {
      delete route.children
    }

    if (route.children && route.children.length > 0) {
      if (!currentRoute.redirect) {
        currentRoute.redirect = route.children[0].path
      }
      ;(currentRoute as RouteRecordRaw).children = generateRoutes(route.children)
    }
    res.push(currentRoute)
  })
  return res
}

//  动态添加路由
export const addRoutes = (routes: any) => {
  // resetRouter()
  // const finalRoutes = generateRoutes(routes)

  routes.forEach((route: any) => {
    router.addRoute(route)
  })

  router.addRoute(NotFoundRoute)

  return routes

  // return finalRoutes
}

export const resetRouter = () => {
  try {
    const newRouter = router
    ;(router as any).matcher = (newRouter as any).matcher // reset router
  } catch (error) {
    // 强制刷新浏览器也行，只是交互体验不是很好
    window.location.reload()
  }
}

export const goChildPath = (data: Array<any> = []): string => {
  console.log('d', data)
  if (data.length > 0) {
    if (!data[0].children || data[0].children.length === 0) {
      return data[0].path
    } else {
      return goChildPath(data[0].children)
    }
  }
  return '/'
}

export default router
